package controllers;

import beans.AlbumBean;
import beans.ArticleBean;
import beans.ArticleCommentBean;
import beans.MailBean;
import beans.PageBean;
import beans.RecommendBean;
import beans.SimpleArticleCommentBean;
import beans.SimpleUserBean;
import beans.TrendBean;
import beans.UserBean;
import beans.WebServiceBean;
import models.Advertisement;
import models.Album;
import models.AlbumArticle;
import models.Article;
import models.ArticleComment;
import models.Attachment;
import models.BigTag;
import models.Collection;
import models.Concern;
import models.FriendshipLink;
import models.Mail;
import models.Photo;
import models.Recommend;
import models.Trend;
import models.User;
import models.WebsiteInfo;
import play.cache.Cache;
import play.db.jpa.GenericModel;
import play.libs.Codec;
import play.libs.Files;
import play.mvc.Controller;
import utils.Config;
import utils.MessageUtil;
import utils.SessionUtils;
import utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xieyicheng on 2014/11/30.
 */
public class Api extends Controller {
    //文章列表
    public static void showArticle(String id,int page,int perpage,int type) {
		List<Article> articlelList;
		String userId = SessionUtils.getUserId();
    	if(type == -1)
    	{
    		long total = Article.count("authorId = ? and isDelete != 1",id);
            page = page <= 0 ? 1 : page;
            PageBean pageBean = PageBean.getInstance(page, total, perpage);
            articlelList = Article.find(
                    "authorId = ? and isDelete != 1 and type=? order by weight , createTime desc",id,type).fetch(
                    pageBean.getCurPage(), pageBean.getPerPage());

    	}
    	else if(type == Article.DRAFT)//草稿只能作者自己看到
    	{
    		if(userId == null)
    		{
    			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
    	        webServiceBean.data = "查看草稿请先登录！";
    	        renderJSON(webServiceBean);
    		}
    		if(!SessionUtils.getUserId().equals(id))
    		{
    			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
    	        webServiceBean.data = "没有权限查看他人草稿！";
    	        renderJSON(webServiceBean);
    		}
    		long total = Article.count("authorId = ? and isDelete != 1 and type = ?",id,type);
            page = page <= 0 ? 1 : page;
            PageBean pageBean = PageBean.getInstance(page, total, perpage);
            articlelList = Article.find(
                    "authorId = ? and isDelete != 1 and type = ? order by weight , createTime desc",id,type).fetch(
                    pageBean.getCurPage(), pageBean.getPerPage());
            
            
    	}
    	else
    	{
    		if(userId != null && userId.equals(id))//作者本身
    		{
    			long total = Article.count("authorId = ? and isDelete != 1 and type = ?",id,type);
	            page = page <= 0 ? 1 : page;
	            PageBean pageBean = PageBean.getInstance(page, total, perpage);
	            articlelList = Article.find(
	                    "authorId = ? and isDelete != 1 and type = ? order by weight , createTime desc",id,type).fetch(
	                    pageBean.getCurPage(), pageBean.getPerPage());
    		}
    		else//非作者本身
    		{
	    		long total = Article.count("authorId = ? and is_verify = 1 and isDelete != 1 and type = ?",id,type);
	            page = page <= 0 ? 1 : page;
	            PageBean pageBean = PageBean.getInstance(page, total, perpage);
	            articlelList = Article.find(
	                    "authorId = ? and is_verify = 1 and isDelete != 1 and type = ? order by weight , createTime desc",id,type).fetch(
	                    pageBean.getCurPage(), pageBean.getPerPage());
    		}
    	}
        WebServiceBean webServiceBean = WebServiceBean.getInstance(1);
        webServiceBean.data = ArticleBean.buildList(articlelList);
        renderJSON(webServiceBean);
    }
    
	/**
	 *@author 李宇星
	 *热门文章
	 **/
	public static void getHeatedArticle(int page,int perpage,int type,long time)
	{
		List<Article> articleList;
		if(type == -1)
		{
			long total = Article.count("isDelete != 1 and is_verify = 1 and createTime >= ?",time);
	        page = page <= 0 ? 1 : page;
	        PageBean pageBean = PageBean.getInstance(page, total, perpage);
	        if((page - 1) * 5 >= total)
	        {
	        	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
		        webServiceBean.data = "超出页码！";
		        renderJSON(webServiceBean);
	        }
	        articleList = Article.find("isDelete != 1 and is_verify = 1 and createTime >= ? order by click desc",time).
					fetch(pageBean.getCurPage(),pageBean.getPerPage());
		}
		else
		{
			long total = Article.count("isDelete != 1 and is_verify = 1 and type = ? and createTime >= ?",type,time);
	        page = page <= 0 ? 1 : page;
	        PageBean pageBean = PageBean.getInstance(page, total, perpage);
	        if((page - 1) * 5 >= total)
            {
                WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                webServiceBean.data = "超出页码！";
                renderJSON(webServiceBean);
            }
			articleList = Article.find("isDelete != 1 and is_verify = 1 and type = ? and createTime >= ? order by click desc",type,time).
					fetch(pageBean.getCurPage(),pageBean.getPerPage());
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = ArticleBean.buildList(articleList);
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *最新文章
	 **/
	public static void getNewestArticle(int page,int perpage,int type,long time)
	{
		List<Article> articleList;
		if(type == -1)
		{
			long total = Article.count("isDelete != 1 and is_verify = 1 and createTime >= ?",time);
	        page = page <= 0 ? 1 : page;
	        PageBean pageBean = PageBean.getInstance(page, total, perpage);
	        if((page - 1) * 5 >= total)
	        {
	        	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
		        webServiceBean.data = "超出页码！";
		        renderJSON(webServiceBean);
	        }
			articleList = Article.find("isDelete != 1 and is_verify = 1 and createTime >= ? order by createTime desc",time).
					fetch(pageBean.getCurPage(),pageBean.getPerPage());
		}
		else
		{
			long total = Article.count("isDelete != 1 and is_verify = 1 and type = ? and createTime >= ?",type,time);
	        page = page <= 0 ? 1 : page;
	        PageBean pageBean = PageBean.getInstance(page, total, perpage);
	        if((page - 1) * 5 >= total)
            {
                WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                webServiceBean.data = "超出页码！";
                renderJSON(webServiceBean);
            }
			articleList = Article.find("isDelete != 1 and is_verify = 1 and type = ? and createTime >= ? order by createTime desc",type,time).
					fetch(pageBean.getCurPage(),pageBean.getPerPage());
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = ArticleBean.buildList(articleList);
		renderJSON(webServiceBean);
	}
	
	//文章最新评论10条
	public static void getNewestArticleComment(String articleId)
	{
		List<ArticleComment> commentList = ArticleComment.find("articleId = ? order by createTime desc", articleId).fetch(10);
		List<SimpleArticleCommentBean> result = new ArrayList<SimpleArticleCommentBean>();
		for(int i = 0;i < commentList.size();i++)
		{
			SimpleArticleCommentBean bean = new SimpleArticleCommentBean();
			bean.articleId = commentList.get(i).articleId;
			bean.content = commentList.get(i).comment;
			result.add(bean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = result;
		renderJSON(webServiceBean);
	}
	
	//最受欢迎10个用户
	public static void getPopularUser()
	{
		List<User> userList = User.find("order by fansNum desc").fetch(10);
		List<SimpleUserBean> result = new ArrayList<SimpleUserBean>();
		for(int i = 0;i < userList.size();i++)
		{
			SimpleUserBean bean = new SimpleUserBean();
			bean.id = userList.get(i).id;
			bean.nickName = userList.get(i).nickname;
			result.add(bean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = result;
		renderJSON(webServiceBean);
	}
    
    /**
     *管理员登陆 
     **/
    public static void adminLogin(User account)
    {
    	if(account.isAllNotNull()){
    		
    		User user = User.findByUsername(account.account);
    		if(user!=null){
                if((user.authority == User.Admin || user.authority == User.SuperAdmin) && user.password.equals(account.password)){
                	session.put("Admin_key","true");
                	WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
            		webServiceBean.data = "有管理员权限";
            		renderJSON(webServiceBean);
                    //MessageUtil.generateErrorMsg("你没有管理员权限");
                    //loginPage();
                }
                else if(!user.password.equals(account.password))
                {
                	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                	webServiceBean.data = "密码错误！";
                	renderJSON(webServiceBean);
                }
                else
                {
                	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                	webServiceBean.data = "没有管理权限！";
                	renderJSON(webServiceBean);
                }
    		}
    		WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
        	webServiceBean.data = "不存在该账号";
        	renderJSON(webServiceBean);
	}
    	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
    	webServiceBean.data = "账号密码不完整";
    	renderJSON(webServiceBean);
    }
    
    /**
     * @author 李宇星
     * 登陆接口
     */
    public static void login(User account){
    	if(account.isAllNotNull()){
    		User user = User.findByUsername(account.account);
    		if(user!=null){
                if(user.password.equals(account.password)){
                	SessionUtils.saveUserId(user.id);
                	WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
            		webServiceBean.data = UserBean.bulid(user);
            		renderJSON(webServiceBean);
                }
                else{
                	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
            		webServiceBean.data = "密码错误";
            		renderJSON(webServiceBean);
                }
    		}
    		else{
    			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
        		webServiceBean.data = "账号不存在";
        		renderJSON(webServiceBean);
    			//MessageUtil.generateErrorMsg("账号不存在");
    			//loginPage();
    		}

    	}
    	else{
    		WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
    		webServiceBean.data = "账号或者密码错误";
    		renderJSON(webServiceBean);
    		//MessageUtil.generateErrorMsg("账号或者密码错误");
    		//loginPage();
    	}
    }
    
    /**
     * @author 李宇星
     * 注销接口
     */
    public static void logout()
    {
    	SessionUtils.clear();
    	WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "注销成功！";
		Application.login();
    }

    /**
     * 注册接口
     * @author 李宇星
     * @param account
     * @param repassword
     * @param randomID
     */
    public static void addUser(User account,String repassword,String validate,String randomID){
        if(account.isAllNotNull()&&StringUtils.isNotEmpty(repassword)&&StringUtils.isNotEmpty(validate)){
            //验证验证码
            String val = "";
            if( Cache.get(randomID)!=null){
                val =  Cache.get(randomID).toString().toLowerCase();
            }
                validation.equals(
                        validate.toLowerCase(),val
                ).message("Invalid code. Please type it again");
            System.out.println(val);
            System.out.println(validate.toLowerCase());
                if (validation.hasErrors()) {
                    //验证出错的操作
                    WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                    webServiceBean.data = "验证码错误";
                    renderJSON(webServiceBean);
                }

            //两次密码输入是否一致
            if(!account.password.equals(repassword)){
            	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
        		webServiceBean.data = "两次密码输入不一致";
        		renderJSON(webServiceBean);
                //flash
                //flash.put("info", "password error");
                //register();
            }
            User user = User.findByUsername(account.account);
            if(user==null){
                //如果找不到，新建用户
                user = new User();
                if(account.email!=null)
				{
					if(!User.matchTheEmail(account.email))
					{
						WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                		webServiceBean.data = "邮箱格式错误！";
                		renderJSON(webServiceBean);
					}
					user.email = account.email;
				}
				if(account.phone!=null)
				{
					if(!User.matchThePhoneNO(account.phone))
					{
						WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                		webServiceBean.data = "手机格式错误！";
                		renderJSON(webServiceBean);
					}
					user.phone = account.phone;
				}
				user.address = account.address;
				user.workArea = account.workArea;
                user.account = account.account;
                user.password = account.password;
                user.nickname="佚名";
                user.save();
                SessionUtils.saveUserId(user.id);
                WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
        		webServiceBean.data = "注册成功";
        		renderJSON(webServiceBean);
                //registerSuccess();
            }
            else{
            	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
        		webServiceBean.data = "该账号已被注册！";
        		renderJSON(webServiceBean);
                //flash.put("info", "has registered");
                //register();
            }
        }
        else{
        	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
    		webServiceBean.data = "注册信息不完整！";
    		renderJSON(webServiceBean);
            //flash.put("info", "info error");
            //register();
        }
    	
    	
    	
    }
    
    /**
     * @author 李宇星
     * 修改个人信息
     */
    public static void modifyInfo(User user){
    	if(user.isAllNotNull()&&user.id!=null&&SessionUtils.getLoginUser()!=null)
    	{
    		User oldUser = User.findById(user.id);
    		if(oldUser!=null)
    		{
    			if(user.password.equalsIgnoreCase(oldUser.password)&&user.account.equalsIgnoreCase(oldUser.account))
    			{
    				if(user.email!=null)
    				{
    					if(!User.matchTheEmail(user.email))
    					{
    						WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
	                		webServiceBean.data = "邮箱格式错误！";
	                		renderJSON(webServiceBean);
    					}
    				}
    				if(user.phone!=null)
    				{
    					if(!User.matchThePhoneNO(user.phone))
    					{
    						WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
                    		webServiceBean.data = "手机格式错误！";
                    		renderJSON(webServiceBean);
    					}
    				}
    				user.save();
    				WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
            		webServiceBean.data = "修改成功";
            		renderJSON(webServiceBean);
    			}
    			else
    			{
    				WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
            		webServiceBean.data = "密码错误";
            		renderJSON(webServiceBean);
    			}
    		}
    		else
    		{
    			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
        		webServiceBean.data = "用户不存在";
        		renderJSON(webServiceBean);
    		}
    	}
    	else
    	{
    		WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
    		webServiceBean.data = "用户信息不完整！";
    		renderJSON(webServiceBean);
    	}
    }
    
    /**
     * 修改密码
     **/
    public static void modifyPassword(String password,String newPassword,String rePassword)
    {
    	String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		User user = User.findById(userId);
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "用户不存在!";
			renderJSON(webServiceBean);
		}
		if(!user.password.equals(password))
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "密码错误！";
			renderJSON(webServiceBean);
		}
		if(!newPassword.equals(rePassword))
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "两次密码不一致！";
			renderJSON(webServiceBean);
		}
		user.password = newPassword;
		user.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "修改成功！";
		renderJSON(webServiceBean);
    }
    
	/**
	 * @author 李宇星
	 * 保存文章接口
	 */
	public static void addArticle(Article article) {
		if(SessionUtils.getLoginUser() != null)
		{
			if(StringUtils.isEmpty(article.content))
			{
				WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
	    		webServiceBean.data = "内容不能为空！";
	    		renderJSON(webServiceBean);
			}
			else if(StringUtils.isEmpty(article.copyRight))
			{
				WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
	    		webServiceBean.data = "版权不能为空!";
	    		renderJSON(webServiceBean);
			}
			else if(StringUtils.isEmpty(article.title))
			{
				WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
	    		webServiceBean.data = "标题不能为空！";
	    		renderJSON(webServiceBean);
			}
			article.authorId = SessionUtils.getUserId();
			article.save();
			
			User user = SessionUtils.getLoginUser();
			user.articleNum++;
			user.save();
			
			Trend.addTrend(SessionUtils.getUserId(), article.id, Trend.ARTICLE);//新建文章同时要增加一个动态

			WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
			webServiceBean.data = article.id;
			renderJSON(webServiceBean);
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
    		webServiceBean.data = "保存失败,请先登录！";
    		renderJSON(webServiceBean);
		}
		
	}
    
	/**
	 *@author 李宇星
	 *删除文章接口 
	 **/
	public static void deleteArticle(String articleId) {
		Article article = Article.getArticleById(articleId);
		if (article != null && SessionUtils.getLoginUser() != null) {
			if(article.authorId.equals(SessionUtils.getUserId()))
			{
				Trend.deleteTrend(article.id,Trend.ARTICLE);//先删除动态
				Photo.deletePhoto(article.photoId);//删除封面
				Attachment.deleteAttachment(article.attachmentId);//删除附件
				Collection.deleteRelatedCollection(article.id, Collection.WORK);//删除相关的收藏
				article.delete();
				User user = SessionUtils.getLoginUser();
				user.articleNum--;
				user.save();
				
				WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
				webServiceBean.data = "删除成功！";
				renderJSON(webServiceBean);
			}
			else
			{
				WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
				webServiceBean.data = "删除失败，你没有删除该文章的权限！";
				renderJSON(webServiceBean);
			}
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "删除失败，请先登录！";
			renderJSON(webServiceBean);
		}
	}
	
	/**
	 *@author 李宇星
	 *修改文章接口 
	 **/
	public static void modifyArticle(Article article) {
		if(article!=null && article.id!=null && SessionUtils.getLoginUser() != null)
		{
			Article oldArticle = Article.findById(article.id);
			if(oldArticle!=null)
			{
				WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
				webServiceBean.data = "修改成功！";
				renderJSON(webServiceBean);
			}
		}
		WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
		webServiceBean.data = "修改失败，请先登录";
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *访问文章接口 
	 **/
	public static void getArticle(String articleId)
	{
		Article article = Article.getArticleById(articleId);
		if(article!=null)
		{
			article.click++;
			article.save();
			WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
			webServiceBean.data = article;
			renderJSON(webServiceBean);
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在！";
			renderJSON(webServiceBean);
		}
	}
	
	/**
	 * @author 李宇星
	 * 关注接口
	 * */
	public static void concern(String beConcernId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		Concern concern = Concern.findByTwoId(userId, beConcernId);
		if(concern == null)
		{
			Concern c = new Concern();
			c.beConcernId = beConcernId;
			c.concernId = userId;
			c.save();
			
			User user = User.findById(userId);
			User beConcernUser = User.findById(beConcernId);
			user.concernNum++;//关注数加一
			beConcernUser.fansNum++;//粉丝数加一
			user.save();
			beConcernUser.save();
			
			WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
			webServiceBean.data = "关注成功！";
			renderJSON(webServiceBean);
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "error!你已经关注过了对方！";
			renderJSON(webServiceBean);
		}
	}
	
	/**
	 * @author 李宇星
	 * 获取关注的人 接口
	 * */
	public static void getConcernPeople(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		long total = Concern.count("concernId = ?",userId);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Concern> concern = Concern.find("concernId = ? order by createTime desc",userId).
				fetch(pageBean.getCurPage(),pageBean.getPerPage());
		List<User> user = new ArrayList<User>();
		for(int i = 0;i < concern.size();i++)
		{
			User u = User.findById(concern.get(i).beConcernId);
			if(u == null)
				continue;
			user.add(u);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = UserBean.bulidList(user);
		renderJSON(webServiceBean);
		
	}
	
	/**
	 *@author 李宇星
	 *谁关注了我 
	 **/
	public static void getWhoConcernMe(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		long total = Concern.count("beConcernId = ?",userId);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Concern> concernList = Concern.find("beConcernId = ? order by create_time desc", userId).
				fetch(pageBean.getCurPage(), pageBean.getPerPage());
		List<User> user = new ArrayList<User>();
		for(int i = 0;i < concernList.size();i++)
		{
			User u = User.findById(concernList.get(i).concernId);
			if(u == null)
				continue;
			user.add(u);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = user;
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 获取粉丝数
	 * */
	public static void getFansNum()
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = user.fansNum;
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 获取关注数
	 * */
	public static void getConcernNum()
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = user.concernNum;
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 获取用户文章数量
	 * */
	public static void getArticleNum()
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = user.articleNum;
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 新建专辑
	 * */
	public static void addAlbum(Album album)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		album.authorId = userId;
		album.save();
		
		Trend.addTrend(userId, album.id, Trend.ALBUM);//增加动态
		
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "新建成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星 
	 *删除专辑
	 **/
	public static void deleteAlbum(String albumId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		Album album = Album.findById(albumId);
		
		if(album == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "删除失败，专辑不存在!";
			renderJSON(webServiceBean);
		}
		if(!album.authorId.equals(userId))
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "删除失败，你没有删除该专辑的权限！";
			renderJSON(webServiceBean);
		}
		
		Trend.deleteTrend(album.id, Trend.ALBUM);//先删除动态
		Photo.deletePhoto(album.photoId);//删除封面
		Collection.deleteRelatedCollection(album.id, Collection.ALBUM);//删除相关收藏
		album.delete();
		
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "删除成功！";
		renderJSON(webServiceBean);
		
	}
	
	/**
	 * @author 李宇星
	 * 添加专辑文章
	 * */
	public static void addArticleToAlbum(String articleId,String albumId)
	{
		if((Album.getAuthorIdById(albumId).equals(SessionUtils.getUserId()))
				&& (Article.getAuthorIdById(articleId).equals(SessionUtils.getUserId())))
		{
			AlbumArticle tmp = AlbumArticle.find("articleId = ? and albumId = ?", articleId,albumId).first();
			if(tmp != null)
			{
				WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
				webServiceBean.data = "不能重复添加！";
				renderJSON(webServiceBean);
			}
			
			Album album = Album.findById(albumId);
			album.articleNum++;
			album.save();
			AlbumArticle aa = new AlbumArticle();
			aa.albumId = albumId;
			aa.articleId = articleId;
			aa.save();
			WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
			webServiceBean.data = "添加成功！";
			renderJSON(webServiceBean);
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "你没有权限添加该文章到专辑!";
			renderJSON(webServiceBean);
		}
	}
	
	/**
	 * @author 李宇星
	 * 删除专辑文章
	 * */
	public static void deleteArticleOfAlbum(String articleId,String albumId)
	{
		if((Album.getAuthorIdById(albumId).equals(SessionUtils.getUserId()))
				&& (Article.getAuthorIdById(articleId).equals(SessionUtils.getUserId())))
		{
			Album album = Album.findById(albumId);
			album.articleNum--;
			album.save();
			AlbumArticle aa = AlbumArticle.find("articleId = ? and albumId = ?",articleId,albumId).first();
			if(aa != null)
				aa.delete();
			WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
			webServiceBean.data = "删除成功！";
			renderJSON(webServiceBean);
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data= "你没有权限删除专辑该文章!";
			renderJSON(webServiceBean);
		}
	}
	
	/**
	 *@author 李宇星
	 *查看专辑里面的文章
	 **/
	public static void showArticleOfAlbum(String albumId,int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		long total = AlbumArticle.count("albumId = ?",albumId);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
        List<AlbumArticle> aaList = AlbumArticle.find(
                "albumId = ? order by createTime desc",albumId).fetch(
                pageBean.getCurPage(), pageBean.getPerPage());
        List<Article> articleList = new ArrayList<Article>();
        for(int i = 0;i < aaList.size();i++)
        {
        	Article article = Article.findById(aaList.get(i).articleId);
        	if(article == null)
        		continue;
        	articleList.add(article);
        }
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = ArticleBean.buildList(articleList);
		renderJSON(webServiceBean);
		
	}
	
	/**
	 * @author 李宇星
	 * 查看用户的专辑
	 * */
	public static void showAlbum(String id,int page,int perpage)
	{	
		long total = Album.count("authorId = ? and isDelete != 1",id);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
        List<Album> albumList = Album.find(
                "authorId = ? and isDelete != 1 order by createTime desc",id).fetch(
                pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = AlbumBean.bulidList(albumList);
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 收藏作品
	 * */
	public static void collectWork(String articleId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		Collection tmp = Collection.find("owner_id = ? and collect_id = ? and type = ?", userId,articleId,Collection.WORK).first();
		if(tmp != null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "不能重复收藏！";
			renderJSON(webServiceBean);
		}
		Collection collection = new Collection();
		collection.owner_id = userId;
		collection.collect_id = articleId;
		collection.type = Collection.WORK;
		collection.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "收藏成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 收藏专辑
	 * */
	public static void collectAlbum(String albumId)
	{
		Collection collection = new Collection();
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		collection.owner_id = userId;
		collection.collect_id = albumId;
		collection.type = Collection.ALBUM;
		collection.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "收藏成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *返回收藏作品 
	 **/
	public static void showCollectionWork(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		long total = Collection.count("owner_id = ? and type = ?",userId,Collection.WORK);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
        List<Collection> collectionList = Collection.find(
                "owner_id = ? and type = ? order by createTime desc",userId,Collection.WORK).fetch(
                pageBean.getCurPage(), pageBean.getPerPage());
        List<Article> articleList = new ArrayList<Article>();
        for(int i = 0;i < collectionList.size();i++)
        {
        	Article article = Article.findById(collectionList.get(i).collect_id);
        	if(article == null)
        	{
        		continue;
        	}
        	articleList.add(article);
        }
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = ArticleBean.buildList(articleList);
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *返回收藏专辑 
	 **/
	public static void showCollectionAlbum(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		long total = Collection.count("owner_id = ? and type = ?",userId,Collection.ALBUM);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
        List<Collection> collectionList = Collection.find(
                "owner_id = ? and type = ? order by createTime desc",userId,Collection.ALBUM).fetch(
                pageBean.getCurPage(), pageBean.getPerPage());
        List<Album> albumList = new ArrayList<Album>();
        for(int i = 0;i < collectionList.size();i++)
        {
        	Album album = Album.findById(collectionList.get(i).collect_id);
        	if(album == null)
        	{
        		continue;
        	}
        	albumList.add(album);
        }
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = AlbumBean.bulidList(albumList);
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *取消收藏
	 **/
	public static void deleteCollection(String id)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		Collection collection = Collection.findById(id);
		if(collection != null && collection.owner_id.equals(SessionUtils.getUserId()))
		{
			collection.delete();
			WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
			webServiceBean.data = "已取消收藏";
			renderJSON(webServiceBean);
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "你没有权限取消该收藏！";
			renderJSON(webServiceBean);
		}
	}
	
	/**
	 * @author 李宇星
	 * 写信接口
	 **/
	public static void writeMail(Mail mail)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		if(StringUtils.isEmpty(mail.content))
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "发送失败，邮件内容为空！";
			renderJSON(webServiceBean);
		}
        if(User.findById(mail.receive_id) == null)
        {
            WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
            webServiceBean.data = "发送失败，接受者不存在！";
            renderJSON(webServiceBean);
        }
		mail.send_id = userId;
		mail.status = Mail.SENDED;
		mail.save();
        User receiver = User.findById(mail.receive_id);
        receiver.hasEmail = 1;
        receiver.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "发送成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 查信接口
	 * 只查到没有接收过的信
	 **/
	public static void checkMail(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		long total = Mail.count("receive_id = ? and status = ? and is_receive_delete != 1",userId,Mail.SENDED);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Mail> mailList = Mail.find("receive_id = ? and status = ? and is_receive_delete != 1 order by createTime desc", userId,Mail.SENDED)
				.fetch(pageBean.getCurPage(),pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = MailBean.bulidList(mailList);
        User user = SessionUtils.getLoginUser();
        user.hasEmail = 0;
        user.save();
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *接收接口 收了的信不会再出现在查信那里 
	 **/
	public static void receiveMail(String mailId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		Mail mail = Mail.findById(mailId);
		if(mail == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "mail不存在";
			renderJSON(webServiceBean);
		}
		if(!mail.receive_id.equals(userId))
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "你无权接受该mail";
			renderJSON(webServiceBean);
		}
		mail.status = Mail.RECEIVED;
		mail.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "成功接收！";
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 查看已发送的mail
	 **/
	public static void showSendMail(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		long total = Mail.count("send_id = ? and is_send_delete != 1",userId);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Mail> mailList = Mail.find("send_id = ? and is_send_delete != 1 order by createTime desc", userId)
				.fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = MailBean.bulidList(mailList);
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 查看已接收的mail
	 **/
	public static void showReceivedMail(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		long total = Mail.count("receive_id = ? and status = ? and is_receive_delete != 1",userId,Mail.RECEIVED);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Mail> mailList = Mail.find("receive_id = ? and status = ? and is_receive_delete != 1 order by createTime desc", userId,Mail.RECEIVED)
				.fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = MailBean.bulidList(mailList);
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 删除已接收的mail
	 **/
	public static void deleteReceiveMail(String mailId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		String [] mailIdList = mailId.split(" ");
		for(int i = 0;i < mailIdList.length;i++)
		{
			Mail mail = Mail.findById(mailIdList[i]);
			if(mail!=null&&!mail.receive_id.equals(userId))
			{
				continue;
			}
			mail.is_receive_delete = 1;
			mail.save();
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "删除成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 删除已发送的mail
	 **/
	public static void deleteSendMail(String mailId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		String [] mailIdList = mailId.split(" ");
		for(int i = 0;i< mailIdList.length;i++)
		{
			Mail mail = Mail.findById(mailIdList[i]);
			if(!mail.send_id.equals(userId))
			{
				continue;
			}
			mail.is_send_delete = 1;
			mail.save();
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "删除成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 * 我的动态
	 **/
	public static void getMyTrend(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}

		long total = Trend.count("owner_id = ?",userId);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Trend> trendList = Trend.find("owner_id = ? order by createTime desc", userId).
				fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = TrendBean.bulidList(trendList);
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 * 关注动态
	 **/
	public static void getConcernTrend(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		long total = Trend.count("select count(*) from Trend trend where trend.owner_id in (select beConcernId from Concern concern where concernId = ?)",userId);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Trend> trendList = Trend.find("select trend from Trend trend where trend.owner_id in (select beConcernId from Concern concern where concernId = ?)  order by Trend.createTime desc", userId).
				fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = TrendBean.bulidList(trendList);
		renderJSON(webServiceBean);
	}
	
	/**
	 *上传文章封面 
	 **/
	public static void uploadArticlePhoto(String articleId, File image,File file,String photoId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		Article article = Article.findById(articleId);

		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "不存在文章";
			renderJSON(webServiceBean);
		}
        if(photoId!=null){
            article.photoId = photoId;
        }
		if(image!=null){
            String imgName=image.getName();
            String unique = Codec.UUID().replace("-", "").toUpperCase();
            File storeFile=new File(Config.imagePath+unique+imgName);
            Files.copy(image, storeFile);
            Photo photo = Photo.addPhoto(unique+imgName,null);
            article.photoId = photo.id;
        }
        if(file!=null){
            String fileName = file.getName();
            String unique_file = Codec.UUID().replace("-", "").toUpperCase();
            File storeFile_file=new File(Config.attachmentPath+unique_file+fileName);
            Files.copy(file, storeFile_file);
            Attachment attachment = Attachment.addAttachment(unique_file + fileName);
            article.attachmentId = attachment.id;
        }
        article.save();
        Members.work(0);
    }
	
	
	/**
	 *上传专辑封面 
	 **/
	public static void uploadAlbumPhoto(String albumId, File image) 
	{	 
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		Album album = Album.findById(albumId);
		if(album == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "不存在专辑!";
			renderJSON(webServiceBean);
		}
		
        String imgName=image.getName();
        String unique = Codec.UUID().replace("-", "").toUpperCase();
        File storeFile=new File(Config.imagePath+unique+imgName);
        Files.copy(image, storeFile);
        Photo photo = Photo.addPhoto(unique+imgName,null);
        album.photoId = photo.id;
        album.save();
        
        WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "上传成功！";
		renderJSON(webServiceBean);
    }
	
	/**
	 *上传头像
	 **/
	public static void uploadUserPhoto(File image) 
	{	 
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
        String imgName=image.getName();
        String unique = Codec.UUID().replace("-", "").toUpperCase();
        File storeFile=new File(Config.imagePath+unique+imgName);
        Files.copy(image, storeFile);
        Photo photo = Photo.addPhoto(unique + imgName, null);
        user.photoId = photo.id;
        user.save();
        Members.home(0);
    }
	
	/**
	 *@author 李宇星
	 *上传附件 
	 **/
	public static void uploadAttachment(File file,String articleId)
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		Article article = Article.getArticleById(articleId);
		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在！";
			renderJSON(webServiceBean);
		}
		
		String fileName = file.getName();
		String unique = Codec.UUID().replace("-", "").toUpperCase();
        File storeFile=new File(Config.attachmentPath+unique+fileName);
        Files.copy(file, storeFile);
        Attachment attachment = Attachment.addAttachment(unique + fileName);
        article.attachmentId = attachment.id;
        article.save();
        
        WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "上传成功！";
		renderJSON(webServiceBean);
	}
	

	
	/**
	 *查看广告 
	 **/
	public static void getAdvertisement(int page,int perpage)
	{
		long total = Advertisement.count("");
		page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
        List<Advertisement> adList = Advertisement.find("order by createTime desc")
        		.fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = adList;
		renderJSON(webServiceBean);
	}
	
	//删除广告
	public static void deleteAdvertisement(String adId)
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		if(user.authority != User.Admin && user.authority != User.SuperAdmin)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "您没有权限！";
			renderJSON(webServiceBean);
		}
		Advertisement ad = Advertisement.findById(adId);
		if(ad == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "不存在该广告！";
			renderJSON(webServiceBean);
		}
		File file = new File(ad.url);
		if(file.exists())
		{
			file.delete();
		}
		ad.remove();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "删除成功！";
		renderJSON(webServiceBean);
	}

	//评论文章
	public static void commentArticle(String articleId,String comment)
	{
		Article article = Article.findById(articleId);
		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在！";
			renderJSON(webServiceBean);
		}
		if(article.is_permit_comment == 1)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不允许评论！";
			renderJSON(webServiceBean);
		}
		User user = SessionUtils.getLoginUser();
		article.commentNum++;
		article.save();
		ArticleComment ac = new ArticleComment();
		ac.comment = comment;
		ac.articleId = articleId;
		if(user != null){
            ac.commentId = user.id;
            ac.type=ArticleComment.USER;
        }
        else{
            ac.type=ArticleComment.VISITOR;
        }
		ac.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "评论成功！";
		renderJSON(webServiceBean);
	}
	
	//获取评论
	public static void getArticleComment(String articleId,int page)
	{
		Article article = Article.findById(articleId);
		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在！";
			renderJSON(webServiceBean);
		}
		long total = ArticleComment.count("articleId = ?",articleId);
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, 5);
        if((page - 1) * 5 >= total)
        {
        	WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
	        webServiceBean.data = "超出页码！";
	        renderJSON(webServiceBean);
        }
		List<ArticleComment> commentList = ArticleComment.find("articleId = ? order by createTime desc", articleId).
				fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = ArticleCommentBean.buildList(commentList);
		renderJSON(webServiceBean);
	}
	
	//获取评论数
	public static void getCommentNum(Article articleId)
	{
		Article article = Article.findById(articleId);
		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在！";
			renderJSON(webServiceBean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = article.commentNum;
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *审核文章接口
	 **/
	public static void verifyArticle(String articleId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		Article article = Article.findById(articleId);
		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在";
			renderJSON(webServiceBean);
		}
		article.is_verify = 1;
		article.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "审核通过！";
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *获取未通过审核的文章 
	 **/
	public static void getNotVerifyArticle(int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		long total = Article.count("is_verify = 0 and is_delete = 0");
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Article> articleList = Article.find("is_verify = 0 and is_delete = 0 order by createTime desc", userId).
				fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = ArticleBean.buildList(articleList);
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *添加tag到文章 
	 **/
	public static void addTagToArticle(String tag,String articleId)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		Article article = Article.findById(articleId);
		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在！";
			renderJSON(webServiceBean);
		}
		if(!article.authorId.equals(userId))
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "无权限添加！";
			renderJSON(webServiceBean);
		}
		article.tag = tag;
		article.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "添加成功!";
		renderJSON(webServiceBean);
		
	}
	
	/**
	 *@author 李宇星
	 *模糊搜索文章 
	 **/
	public static void search(String title,int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		long total = Article.count("title like '%" + title + "%'");
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Article> articleList = Article.find("title like '%" + title + "%'").
				fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = articleList;
		renderJSON(webServiceBean);
	}
	/*根据tag搜索
	public static void search(String tag,int page,int perpage)
	{

		long total = TagArticle.count("select count(distinct articleId) from TagArticle tagArticle,Tag tag where tagArticle.tagId = tag.id and tag.content like '%" + tag + "%'");
        page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
		List<Article> articleList = Article.find("select article from Article article where article.id in (select tagArticle.articleId from TagArticle tagArticle,Tag tag where tagArticle.tagId = tag.id and tag.content like '%" + tag + "%') order by article.createTime desc").
				fetch(pageBean.getCurPage(), pageBean.getPerPage());
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = articleList;
		renderJSON(webServiceBean);
	}*/
	
	public static void getTagOfArticle(String articleId,int page,int perpage)
	{
		String userId = SessionUtils.getUserId();
		if(userId == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		
		Article article = Article.findById(articleId);
		if(article == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章不存在！";
			renderJSON(webServiceBean);
		}
		if(StringUtils.isEmpty(article.tag))
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "文章tag为空!";
			renderJSON(webServiceBean);
		}
		String [] tagList = article.tag.split(" ");
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = tagList;
		renderJSON(webServiceBean);
	}
	
	/**
	 *增加bigTag 
	 **/
	public static void addBigTag(String color,String content)
	{
		if(BigTag.matchTheColor(color) == false)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "颜色格式错误！";
			renderJSON(webServiceBean);
		}
		BigTag tag = new BigTag();
		tag.color = color;
		tag.content = content;
		tag.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "添加成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 *删除bigTag 
	 **/
	public static void deleteBigTag(String id)
	{
		BigTag tag = BigTag.findById(id);
		if(tag == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "tag不存在！";
			renderJSON(webServiceBean);
		}
		tag.delete();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "删除成功！";
		renderJSON(webServiceBean);
	}
	
	 // 获取关于我们
	public static void getAboutUs()
	{
		WebsiteInfo info =WebsiteInfo.find("").first();
		if(info == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "info is null!";
			renderJSON(webServiceBean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = info.aboutUs;
		renderJSON(webServiceBean);
	}
	
	 // 获取联系我们
	public static void getContactUs()
	{
		WebsiteInfo info =WebsiteInfo.find("").first();
		if(info == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "info is null!";
			renderJSON(webServiceBean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = info.contactUs;
		renderJSON(webServiceBean);
	}
	
	 // 获取加入我们
	public static void getJoinUs()
	{
		WebsiteInfo info =WebsiteInfo.find("").first();
		if(info == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "info is null!";
			renderJSON(webServiceBean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = info.joinUs;
		renderJSON(webServiceBean);
	}
	
	 // 意见反馈
	public static void suggestion()
	{
		WebsiteInfo info =WebsiteInfo.find("").first();
		if(info == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "info is null!";
			renderJSON(webServiceBean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = info.suggestion;
		renderJSON(webServiceBean);
	}
	
	 // 获取免责声明
	public static void getDisClaimer()
	{
		WebsiteInfo info =WebsiteInfo.find("").first();
		if(info == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "info is null!";
			renderJSON(webServiceBean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = info.disclaimer;
		renderJSON(webServiceBean);
	}

	// 获取友情链接
	public static void getFriendshipLink(int page,int perpage)
	{
		long total = FriendshipLink.count();
		page = page <= 0 ? 1 : page;
        PageBean pageBean = PageBean.getInstance(page, total, perpage);
        List<FriendshipLink> link = FriendshipLink.find("order by createTime desc").
        		fetch(pageBean.getCurPage(),pageBean.getPerPage());
        WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = link;
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *编辑网站信息
	 *@param type 关于我们 = 1 联系我们 = 2 加入我们 = 3 意见反馈 = 4 免责声明 = 5 
	 **/
	public static void editWebsiteInfo(int type,String content)
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		if(user.authority != User.Admin && user.authority != User.SuperAdmin)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "您没有权限修改信息！";
			renderJSON(webServiceBean);
		}
		WebsiteInfo info =WebsiteInfo.find("").first();
		if(info == null)
			info = new WebsiteInfo();
		if(type == 1)
		{
			info.aboutUs = content;
			info.save();
		}
		else if(type == 2)
		{
			info.contactUs = content;
			info.save();
		}
		else if(type == 3)
		{
			info.joinUs = content;
			info.save();
		}
		else if(type == 4)
		{
			info.suggestion = content;
			info.save();
		}
		else if(type == 5)
		{
			info.disclaimer = content;
			info.save();
		}
		else
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "不存在该种信息！";
			renderJSON(webServiceBean);
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "修改成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 * 增加友情链接
	 **/
	public static void addLink(String url,String discription)
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		if(user.authority != User.Admin && user.authority != User.SuperAdmin)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "您没有权限！";
			renderJSON(webServiceBean);
		}
		FriendshipLink link = new FriendshipLink();
		link.description = discription;
		link.url = url;
		link.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "添加成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 * @author 李宇星
	 * 编辑友情链接
	 **/
	public static void editLink(FriendshipLink link)
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		if(user.authority != User.Admin && user.authority != User.SuperAdmin)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "您没有权限！";
			renderJSON(webServiceBean);
		}
		FriendshipLink tmp = FriendshipLink.findById(link.id);
		if(tmp == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "不存在该链接";
			renderJSON(webServiceBean);
		}
		link.save();
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "编辑成功！";
		renderJSON(webServiceBean);
	}
	
	/**
	 *@author 李宇星
	 *删除友情链接 
	 *@param linkId 链接id空格分开
	 **/
	public static void deleteLink(String linkId)
	{
		User user = SessionUtils.getLoginUser();
		if(user == null)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "请先登录！";
			renderJSON(webServiceBean);
		}
		if(user.authority != User.Admin && user.authority != User.SuperAdmin)
		{
			WebServiceBean webServiceBean = WebServiceBean.getFailInstance();
			webServiceBean.data = "您没有权限！";
			renderJSON(webServiceBean);
		}
		String [] linkList = linkId.split(" ");
		FriendshipLink tmp;
		for(int i = 0;i < linkList.length;i++)
		{
			tmp = FriendshipLink.findById(linkList[i]);
			if(tmp == null)
				continue;
			tmp.delete();
		}
		WebServiceBean webServiceBean = WebServiceBean.getSuccessInstance();
		webServiceBean.data = "删除成功！";
		renderJSON(webServiceBean);
	}
	
}
